package blog.caidabao.controller;

import blog.caidabao.pojo.Article;
import blog.caidabao.pojo.IndexArticle;
import blog.caidabao.service.ArticleService;
import blog.caidabao.service.RedisService;
import blog.caidabao.utils.MyUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.ZSetOperations;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.util.Iterator;
import java.util.List;
import java.util.Set;

@RestController
@RequestMapping("article")
public class ArticleController {
    @Autowired
    private ArticleService articleService;

    @Autowired
    private RedisService redisService;

    @GetMapping("/findById/{id}")
    public ResponseEntity<Article> queryArticleById(@PathVariable("id") Integer id){
        Article article=this.articleService.queryArticleById(id);
        if(article==null){
            return new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR);

        }
        return ResponseEntity.ok(article);
    }


    @PostMapping("save")
    @Transactional
    public ResponseEntity<Boolean> saveArticle(@RequestParam("articleTitle") String articleTitle,
                                               @RequestParam("articleContent") String articleContent,
                                               @RequestParam("articleCategoryId") Integer articleCategoryId,
                                               @RequestParam("articleDesc") String articleDesc){
        Article article=new Article(articleTitle,articleContent,articleCategoryId,articleDesc);
        Boolean bool=this.articleService.saveArticle(article);
        Integer articeId=this.articleService.getLastInsertId();//获取最新自增的id即刚刚创建的文章id
        this.redisService.addArticleViewTimes(articeId);//文章阅读数添加到redis中
        if (bool==null||!bool){
            return ResponseEntity.status(HttpStatus.BAD_REQUEST).build();
        }
        return new ResponseEntity<>(HttpStatus.CREATED);
    }

    @PostMapping("edit")
    @Transactional
    public ResponseEntity<Boolean> editArticle(
                                               @RequestParam("id") Integer id,
                                               @RequestParam("articleTitle") String articleTitle,
                                               @RequestParam("articleContent") String articleContent,
                                               @RequestParam("articleCategoryId") Integer articleCategoryId,
                                               @RequestParam("articleDesc") String articleDesc){
        Article article=new Article(id,articleTitle,articleContent,articleCategoryId,articleDesc);
        Boolean bool=this.articleService.editArticle(article);
        if (bool==null||!bool){
            return ResponseEntity.status(HttpStatus.BAD_REQUEST).build();
        }
        return new ResponseEntity<>(HttpStatus.CREATED);
    }

    @GetMapping("all")
    public ResponseEntity<List<Article>> articleAll(){
        List<Article> articles = this.articleService.articleAll();
        return ResponseEntity.ok(articles);
    }


    @DeleteMapping("delete/{id}")
    public ResponseEntity<String> articleDelte(@PathVariable("id") Integer id){
       Boolean result=this.articleService.articleDelete(id);
       if (result==true){
           return ResponseEntity.ok("删除成功！");
       }
       return ResponseEntity.ok("删除失败！");
    }


    @GetMapping("index")
    public ResponseEntity<List<IndexArticle>> articleindex(){

        Set rangeSet=this.redisService.revrangeWithScore("article_range",0,-1);//获取阅读量排行信息
        String idsStr= MyUtils.getIds(rangeSet);
        List<IndexArticle> indexArticles=this.articleService.indexArticles(idsStr);
        if(indexArticles==null){
            return new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR);

        }//把阅读量写入相应的文章
        Iterator<IndexArticle> iterator=indexArticles.iterator();
        Iterator<ZSetOperations.TypedTuple<Integer>> iterator2 = rangeSet.iterator();
        while (iterator.hasNext()){
            iterator.next().setArticleViewTimes(iterator2.next().getScore());
        }

        return ResponseEntity.ok(indexArticles);
    }

    @PutMapping("/articleViewTimes/{articleId}")
    @ResponseBody
    public void articleViewtimesIncr(@PathVariable("articleId") Integer id){
        this.redisService.articleViewTimesIncr(id);
    }

    @GetMapping("articleViewTimes/{articleId}")
    public ResponseEntity<Double> GetArticleViewTimes(@PathVariable("articleId") Integer id){
        return ResponseEntity.ok(this.redisService.getArticleViewTimes(id));
    }

    @GetMapping("newestArticles")
    public ResponseEntity<List<Article>> newestArticles(){
        List<Article> articles = this.articleService.newestArticles();
        if(articles==null){
            return new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR);

        }
        return ResponseEntity.ok(articles);
    }

    @GetMapping("category/{id}")
    public ResponseEntity<List<IndexArticle>> findArticleByCategoryId(@PathVariable Integer id){
        List<IndexArticle> articles=this.articleService.findArticleByCategoryId(id);
        if(articles==null){
            return new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR);

        }
        return ResponseEntity.ok(articles);
    }

    @GetMapping("search/{searchContent}")
    public ResponseEntity<List<Article>> search(@PathVariable("searchContent") String searchContent){
        List<Article> articles = this.articleService.search(searchContent);
        if(articles==null){
            return new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR);

        }
        return ResponseEntity.ok(articles);
    }

    @GetMapping("/count")
    public ResponseEntity<Integer> count(){
        return ResponseEntity.ok(this.articleService.count());
    }


    @GetMapping("/page/{pageNum}")
    public ResponseEntity<List<Article>> getArticleByPage(@PathVariable("pageNum") Integer pageNum){
        List<Article> articles=this.articleService.getArticleByPage(pageNum);

        if (articles==null)
            return new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR);

        return ResponseEntity.ok(articles);
    }
}
